package com.bdbit.ChargingStation;


import com.bdbit.ChargingStation.Utils.GsonUtils;
import com.bdbit.ChargingStation.Utils.HttpClientUtil;
import com.bdbit.ChargingStation.Utils.TimeUtils;
import com.bdbit.ChargingStation.config.MqttClientConfig;
import com.bdbit.ChargingStation.entity.bean_base_order;
import com.bdbit.ChargingStation.wx.WxConfig;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.mybatis.spring.annotation.MapperScan;
import org.mybatis.spring.annotation.MapperScans;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.scheduling.annotation.EnableScheduling;

import javax.management.MBeanServer;
import javax.management.ObjectName;
import java.lang.management.ManagementFactory;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.Map;
import java.util.TimeZone;

//import static com.baomidou.mybatisplus.extension.ddl.DdlScriptErrorHandler.PrintlnLogErrorHandler.log;
import static java.lang.Thread.sleep;


@Slf4j
@SpringBootApplication
@EnableScheduling
@MapperScans(value = {
        @MapperScan("com.bdbit.ChargingStation.dao.mapper"),
        @MapperScan("com.bdbit.ChargingStation.mapper")
})
//@EnableScheduling  // 启用定时任务
/**
 * 系统启动类
 * 主要功能：
 * 1. 启动Spring Boot应用
 * 2. 开启定时任务处理订单状态
 * 3. 初始化MQTT客户端
 */
public class ChargingStationApplication {
    @Autowired
    private JdbcTemplate jct;
    
    @Value("${server.port:8089}")
    private String serverPort;
    
    @Value("${springdoc.swagger-ui.path:/swagger-ui.html}")
    private String swaggerPath;

    /**
     * 应用程序主入口
     * @param args 启动参数
     */
    public static void main(String[] args) {
        TimeZone.setDefault(TimeZone.getTimeZone("Asia/Shanghai"));
        try {
            // 在Spring启动前加载私钥
            WxConfig.privateKey = WxConfig.readCertContent("wxpay/apiclient_key.pem");
            log.info("私钥加载成功，长度: {}", WxConfig.privateKey.length());

            SpringApplication.run(ChargingStationApplication.class, args);
        } catch (Exception e) {
            log.error("应用启动失败", e);
        }

        /**
         * 创建并启动后台线程用于定期处理订单状态
         * 功能说明：
         * 1. 每分钟执行一次订单状态检查
         * 2. 获取超时5分钟的订单并更新状态为3（已取消）
         * 3. 通过HTTP接口与订单服务交互
         */
//        new Thread(new Runnable() {
//            @Override
//            public void run() {
//                while (true) {
//                    try {
//                        sleep(60000);
//
//                        HttpClientUtil httpClientUtil = new HttpClientUtil();
//                        Map<String, String> maps = new HashMap<>();
//                        // 设置查询参数：获取所有待处理订单
//                        maps.put("status", "2");
//
//                        // 调用订单服务接口获取数据
//                        String json = httpClientUtil.doPost(1, "http://localhost:8089/api/order/GetOrderByType", maps, "utf-8");
//                        bean_base_order order = GsonUtils.josnToModule(json, bean_base_order.class);
//                        long nowtime = TimeUtils.getCurTimeLong();
//
//                        // 遍历订单列表，检查每个订单的创建时间
//                        for (int i = 0; i < order.getData().size(); i++) {
//                            long kaidan_time = Long.parseLong(order.getData().get(i).getKaidan_time());
//
//                            // 判断订单是否超时（5分钟）
//                            if (nowtime - kaidan_time >= 60 * 1000 * 5 && kaidan_time != 0) {
//                                // 更新超时订单状态为已取消
//                                order.getData().get(i).setOrder_status(3);
//                                // 调用接口更新订单状态
//                                httpClientUtil.doPostJson("http://localhost:8089/api/order/UpdataOrderByIds", order.getData().get(i), "utf-8");
//                            }
//                        }
//                    } catch (InterruptedException e) {
//                    }
//                }
//            }
//        }).start();
    }
    private static void cleanExistingMBean() {
        try {
            MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer();
            ObjectName objectName = new ObjectName("org.springframework.boot:type=Admin,name=SpringApplication");
            if (mBeanServer.isRegistered(objectName)) {
                mBeanServer.unregisterMBean(objectName);
                System.out.println("清理旧 MBean 成功");
            }
        } catch (Exception e) {
            System.out.println("清理 MBean 时发生异常: " + e.getMessage());
        }
    }
    /**
     * 启动后自动开启MQTT客户端和定时任务
     */
    @Bean
    public CommandLineRunner init(MqttClientConfig mqttClientConfig,
                                  HttpClientUtil httpClientUtil,
                                  MqttConnectOptions options) { // 添加options参数
        return args -> {
            // 获取服务器IP地址
            String serverAddress = getServerAddress();
            
            // 移除Swagger UI地址打印
            log.info("========================================================");
            log.info("充电站管理系统已启动");
            log.info("========================================================");
        };
    }
    
    /**
     * 获取服务器IP地址
     * @return 服务器IP地址或主机名
     */
    private String getServerAddress() {
        try {
            InetAddress inetAddress = InetAddress.getLocalHost();
            return inetAddress.getHostAddress();
        } catch (UnknownHostException e) {
            log.warn("无法获取服务器IP地址: {}", e.getMessage());
            return "服务器IP";
        }
    }
}